"use strict";

import './main.less';

import Xhr from '../utils/xhr';
import mainHtml from './main.tpl.html';
import main2Html from './main2.tpl.html';
import mainErrorHtml from './main.error.tpl.html';
import Tool from '../utils/tool';

import Modal from '../components/modal';
import {
    showActionSheet
} from '../components/action-sheet';
import AppsInfo from '../utils/apps-info';
import ListData from '../utils/mock-list-data';
import Loading from '../components/loading';
import Workplus from '../utils/workplus';
import Dialog from '../components/modal';
import Constant from '../utils/constant';

export default {
    // initialization page
         pageIndex: 1,
         pageSize: 10,
         loadingMore: false,
         hasMore: false,
         init() {
            this.render();
            // Xhr.getUnread({
            //     reqParams:{
            //         type: "processesCenter"
            //     },
            //     success: function(res){
            //         console.log(res);
            //     },
            //     error: function(){

            //     }
            // })
        },
        render() {
            // Loading.show();
            // Dialog.alert({
            //     text: "调用失败"
            // });
            var self = this;
            Promise.all([self.getUserInfo(), self.getAppInfo(), self.getTheme()])
            .then(function(res){
                console.log('promise success');
                self.initCtx(res);
            })
            .catch(function(err){
                self.initError("错误：初始化数据失败");
            });

        },
        getTheme(){
            return new Promise(function(resolve, reject){
                if(window.cordova){
                    Workplus.getTheme(function(res){
                        resolve(res);
                    })
                }else{
                    resolve();
                }
            })
        },
        getUserInfo(){
            return new Promise(function(resolve, reject){
                if(window.cordova){
                    Workplus.getCurrentUserInfo(function(result){
                        // window.alert(JSON.stringify(result));
                        // alert(result.employee.org_code);
                        // alert(result.employee.domain_id);
                        resolve({
                            orgId: result.employee.org_code,
                            domainId: result.employee.domain_id,
                            username: result.username
                        })
                    },function(err){
                        reject("cordova err");
                    });
                }else{
                    resolve({
                        orgId: "18590d66-26fe-4e78-9344-496370670ccf",
                        domainId: "rfchina",
                        username: "maoguodao"
                    })
                }
            })
        },
        getAppInfo() {
            var self = this;
            return new Promise(function(resolve, reject){
         
                if (self._getQueryString("type")) {
                    // find方法有问题？
                    var filterArr = AppsInfo.filter(function(item){
                        return item.type == self._getQueryString("type");
                    });
                    window.currentApp = filterArr[0];
                    
                    // window.history.replaceState(null, "", "/");

                    resolve(window.currentApp);
                } else {
                    // window.currentApp = AppsInfo[3];
                    if (window.currentApp) {
                        resolve(window.currentApp);
                    } else {
                        reject("错误：未找到应用信息");
                    }
                }
            })

        },
        initCtx(res) {
            var currentUser = res[0];
            var currentApp = res[1];
            var currentTheme = res[2];
            var defaultTabIndex = 0;
            var titleColor = this.getTitleColor(currentTheme);
            
            if(currentApp.type !== "newcir5"){ 
                // 配置
                var tpl = Tool.renderTpl(mainHtml, {
                    hasTabs: currentApp.tabs || false,
                    tabs: currentApp.tabs || {}
                });
                // 渲染
                $('.home-page').html(tpl);
                // 输入值
                if (currentApp.tabs) { 
                    this.setActiveTab(defaultTabIndex);
                };
                this.initList(res);
            }else{
                Loading.hide();
                var tpl = Tool.renderTpl(main2Html);
                $('.home-page').html(tpl);

            }
            $('.navbar-custom').css("background", titleColor);
            $('.title-value').html(currentApp.name);
            this.bindEvent();

        },
        initError(info) {
            var tpl = Tool.renderTpl(mainErrorHtml, {
                errorInfo: info
            });
            // 渲染
            $('.title-value').html("error");
            $('.home-page').html(tpl);
            this.getDone();
        },
        initList(res) {
            var self = this;
            var myApp = new Framework7();
            var $$ = Dom7;
            this.getListData(res, "refresh", this.pageIndex);
            // 下拉刷新
            $$('.pull-to-refresh-content').on('refresh', function(e) {
                console.log(1);
                // 模拟2s的加载过程
                // setTimeout(function() {
                    // self.getListData(res, "refresh");
                // }, 2000);
            });
            // 上拉加载 infinite-scroll
            // $$('.infinite-scroll').on('infinite', function () {
            //     if(self.loadingMore)return;
            //     if(window.currentApp.type !== "processesCenter"){
            //         self.getMoreItemDone();
            //         return;
            //     };
            //     self.loadingMore = true;
            //     var lastIndex = $$('.list-block li').length;
            //     var currentIndex = Math.ceil(lastIndex/self.pageSize);
            //     // if (!self.hasMore) {
            //     //     myApp.detachInfiniteScroll($$('.infinite-scroll'));
            //     //     $$('.infinite-scroll-preloader').remove();
            //     //     return;
            //     // }
            //     var nextPageIndex = parseInt(currentIndex) + 1;
            //     self.getListData(res, "append", nextPageIndex);
            // })
        },
        hasMoreItem(res){
            // 只有流程中心有分页
            if(window.currentApp.type !== "processesCenter"){
                this.getMoreItemDone();
                return;
            };
            if(res.length == this.pageSize){
                this.hasMore = true;
            }else if (res.length < this.pageSize){
                this.hasMore = false;
                this.getMoreItemDone();
            }else{
                console.error("出错拉～");
                this.getMoreItemDone();
            }
            console.log("hasMore", this.hasMore);
        },
        getMoreItemDone(){
            var myApp = new Framework7();
            var $$ = Dom7;
            self.loadingMore = false;
            myApp.detachInfiniteScroll($$('.infinite-scroll'));
            $$('.infinite-scroll-preloader').remove();
        },
        getListData(res, type, pageIndex) {
            var self = this;
            var currentUser = res[0];
            var currentApp = res[1];

            var tabType = currentApp.tabs?currentApp.tabs[window.currentTabIndex].type:"";

            // this.renderListData(ListData);
            Xhr.getList({
                reqParams:{
                    type: currentApp.type
                },
                data:{
                    tabType: tabType,
                    user: currentUser.username,
                    orgId: currentUser.orgId,
                    domainId: currentUser.domainId,
                    pageIndex: pageIndex || 1,
                    pageSize: self.pageSize
                },
                success: function(res, status){
                    console.log(res);
                    if(res.status == 0){
                        // self.hasMoreItem(res.result);
                        self.renderListData(res.result, type);
                    }else{
                        self.initError("列表数据请求失败。")
                    }
                },
                error: function(err){
                    self.initError("列表数据请求失败。")
                }
            })
        },
        renderListData(data, type){
            var myApp = new Framework7();
            var $$ = Dom7;
            var self = this;
            // var data = ListData;
            console.log(type);
            var base64 = "";
            var ptrContent = $$('.pull-to-refresh-content');

            // if(type == "append"){
            //     this.isAppendItemToList(data);
            // }else if (type == "refresh"){
            //     this.isRefreshList(data);
            // }

            if (data.length > 0) {
                data.forEach(function(item) {
                    var hasImage = (item.image_url)?'<div class="item-img-wrapper">' +
                            '<img class="item-img" src='+ item.image_url +' alt="">' +
                        '</div>':"";
                    var formatTime = (item.publish_time.length>10)?item.publish_time.substr(0,10):item.publish_time;
                    var itemHTML = '<li class="item" data-url='+ item.link_url +'>' + hasImage +
                        '<div class="item-ctx">' +
                            '<div class="item-title-info">'+item.title+'</div>' +
                            '<div class="item-subtitle">' +
                                '<div class="publish-time">'+ formatTime +'</div>' +
                           ' </div>' +
                        '</div>' +
                        '<div class="item-flag">' +
                           ' <img src='+base64+' alt="">' +
                        '</div>' +
                    '</li>';
                    // 前插新列表元素
                    ptrContent.find('ul').prepend(itemHTML);
                })
            } else {
                if ($('.pull-to-refresh-content').find('.no-data').length == 0) {
                    var noDataHTML = '<div class="no-data">暂无数据，下拉刷新数据。</div>';
                    $('.pull-to-refresh-content').append(noDataHTML);
                };
            }
            // 加载完毕需要重置
            myApp.pullToRefreshDone();
            setTimeout(function() {
                self.getDone();
            }, 300);
        },
        renderList(data){
            var $$ = Dom7;
            var ptrContent = $$('.pull-to-refresh-content');
            var base64 = "";

            data.forEach(function(item) {
                var hasImage = (item.image_url)?'<div class="item-img-wrapper">' +
                        '<img class="item-img" src='+ item.image_url +' alt="">' +
                    '</div>':"";
                var formatTime = (item.publish_time.length>10)?item.publish_time.substr(0,10):item.publish_time;
                var itemHTML = '<li class="item" data-url='+ item.link_url +'>' + hasImage +
                    '<div class="item-ctx">' +
                        '<div class="item-title-info">'+item.title+'</div>' +
                        '<div class="item-subtitle">' +
                            '<div class="publish-time">'+ formatTime +'</div>' +
                       ' </div>' +
                    '</div>' +
                    '<div class="item-flag">' +
                       ' <img src='+base64+' alt="">' +
                    '</div>' +
                '</li>';
                // 前插新列表元素
                ptrContent.find('ul').prepend(itemHTML);
            })
            var myApp = new Framework7();
            myApp.pullToRefreshDone();
            
        },
        isAppendItemToList(data){
            if(data.length>0){
                this.renderList(data);
            }
        },  
        isRefreshList(data){
            var myApp = new Framework7();
            var $$ = Dom7;
            var self = this;
            var ptrContent = $$('.pull-to-refresh-content');
            ptrContent.find('ul').html("");
            if(data.length > 0 ){
                this.renderList(data);
            }else{
                if ($('.pull-to-refresh-content').find('.no-data').length == 0) {
                    var noDataHTML = '<div class="no-data">暂无数据，下拉刷新数据。</div>';
                    $('.pull-to-refresh-content').append(noDataHTML);
                };
            }
            myApp.pullToRefreshDone();
            setTimeout(function() {
                self.getDone();
            }, 300);
        },
        getDone() {
            var myApp = new Framework7();
            var $$ = Dom7;
            Loading.hide();
            self.loadingMore = false;
        },
        setActiveTab(index) {
            var self = this;
            $('.sub-tab').removeClass('sub-tab-active');
            $('.sub-tab').eq(index).addClass('sub-tab-active');
            window.currentTabIndex = index;
            self.loadingMore = false;
            self.hasMore = false;
        },
        showActionSheet() {
            var btns = [{
                text: 'Alert',
                onClick() {
                    Modal.alert('hello Framework7');
                }
            }, {
                text: 'Confirm',
                onClick() {
                    Modal.confrim('Are you ok?');
                }
            }];
            showActionSheet(btns);
        },
        // bind events
        bindEvent() {
            var $$ = Dom7;
            $('.sub-tab').on('click', this.clickTab.bind(this));
            $('.exit-btn').on('click', this.cliekExitBtn.bind(this));
            var _this = this;
            var bindings = [{
                element: '.list-block',
                event: 'click',
                selector: '.item',
                handler: function(){
                    _this.clickItemEvent($$(this));
                }
            },{
                element: '.main2-list',//我的传阅
                event: 'click',
                selector: 'li',
                handler: function(){
                    _this.clickMain2ItemEvent($$(this));
                }
            }];

            Tool.bindEvents(bindings);
        },
        cliekExitBtn(){
            Workplus.getOut();
        },
        clickTab(e) {
            var self = this;
            var $$ = Dom7;
            var ptrContent = $$('.pull-to-refresh-content');
            ptrContent.find('ul li').remove();
            $$(".no-data").remove();
            // Loading.show();
            this.setActiveTab($(e.currentTarget).index());
            Promise.all([self.getUserInfo(), self.getAppInfo()])
            .then(function(res){
                self.getListData(res, "refresh", 1);
            })
            .catch(function(err){
                self.initError("错误：初始化数据失败");
            });
        },
        clickMain2ItemEvent(currentTarget){
            var targetType = currentTarget[0].attributes["data-id"].nodeValue;
            var filterArr =  window.currentApp.list.filter(function(item){
                return item.type == targetType
            });
            var targetItem = filterArr[0];
            if(Constant.STATUS.ENV == 'DEV'){
                this.openWebView(targetItem.testUrl, window.currentApp.name);
            }else{
                this.openWebView(targetItem.productionUrl, window.currentApp.name);
            }
        },
        clickItemEvent(currentTarget) {
            var self = this;
            console.log(currentTarget[0].attributes["data-url"].nodeValue);

            // var mainView = myApp.addView('.view-main');
            // mainView.router.loadPage('page/detail.html?id=12345')
            this.openWebView(currentTarget[0].attributes["data-url"].nodeValue, window.currentApp.name);
            // if(window.cordova){
            //     Workplus.openAuthNormalWebview({
            //         url: currentTarget[0].attributes["data-url"].nodeValue || "",
            //         title: window.currentApp.name || "404",
            //     },function(res){

            //     })
            // }else{
            //     window.open(currentTarget[0].attributes["data-url"].nodeValue || "")
            // }
        },
        openWebView(url, title){
            if(window.cordova){
                Workplus.openAuthNormalWebview({
                    url: url || "",
                    title: title || "404"
                },function(res){})
            }else{
                window.open(url || "");
            }
        },
        getTitleColor(res){
            if(res && res.base_color){
                return res.base_color.c1;
            }else{
                return "#1A98FF";
            }
        },
        _getQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        }
};